import UNIONWITH from 'lodash/unionWith'
import ISEQUAL from 'lodash/isEqual'
import REMOVE from 'lodash/remove'
import { getPortTable, openPort, closePort, txPort,rxPort, upPortSettings, getPortSettings } from '../../utils/uart'
import { readCSV } from '../../utils/import-csv'
import MARGE from 'lodash/merge'
import moment from "moment";


const state = {
  hardConfTbl: [],
  curPorts: [],
  openPortsObj: [],
  message: {},
  readTimer:10,
  showType:"Hex",
}

const getters = {
  getHardConfTbl: state => {
    return state.hardConfTbl
  },
  getCurPorts: state => {
    return state.curPorts
  },
  getMessage:state=>{
    return state.message
  },
  getReadTimer:state=>{
    return state.readTimer
  },
  getShowType:state=>{
    return state.showType
  }
}

const mutations = {
  ADD_NEW_HARDCFG(state, item) {
    state.hardConfTbl = UNIONWITH(state.hardConfTbl, item, ISEQUAL)
  },
  UPPER_ONE_HARDCFG(state, { item, index }) {
    MARGE(state.hardConfTbl[index], item)
  },
  DEL_HARDCFG(state, index) {
    state.hardConfTbl.splice(index, 1)
  },
  GOT_CURPORTS(state, table) {
    state.curPorts = MARGE(table, state.curPorts)
  },
  AUTOUP_CURPORTS(state, table) {
    state.curPorts = table
  },
  ADD_OPENPORTOBJ(state, path) {
    state.openPortsObj = UNIONWITH(state.openPortsObj, path, ISEQUAL)
    state.curPorts.forEach((port) => {
      if (port.path == path) {
        port.open = true;
      }
    });
  },
  DEL_OPENPORTOBJ(state, path) {
    state.openPortsObj = REMOVE(state.openPortsObj, function (item) {
      return item == path
    })
    state.curPorts.forEach((port) => {
      if (port.path == path) {
        port.open = false;
      }
    });
  },
  UPPER_READMESSAGE(state,{port,readMessage}) {
    moment.locale('zh-cn')
    state.message = {
      port: port,
      type: "Rx",
      text: moment().format("L HH:mm:ss.SSS ")+' '+port+' Rx: '+readMessage
    }
  },
  UPPER_SENDMESSAGE(state, { port, sendMessage }) {
      moment.locale('zh-cn')
    state.message = {
      port: port,
      type: "Tx",
      text: moment().format("L HH:mm:ss.SSS ")+' '+port+' Tx: '+sendMessage
    }
  },
  UPPER_READ_TIMER(state,timer){
    state.readTimer = timer
  },
  UPPER_SHOW_TYPE(state,type){
    state.showType = type
  }
}

const actions = {
  addNewHardCfg({ commit }, newItem) {
    commit('ADD_NEW_HARDCFG', newItem)
  },
  updataOneHardCfg({ commit }, { item, index }) {
    commit('UPPER_ONE_HARDCFG', { item, index })
  },
  async addCsvCfg({ commit }, data) {
    commit('ADD_NEW_HARDCFG', await readCSV(data.file, data.keyMap))
  },
  delHardCfg({ commit }, index) {
    commit('DEL_HARDCFG', index)
  },
  async gotCurPorts({ commit }) {
    commit('GOT_CURPORTS', await getPortTable())
  },
  async autoupCurPorts({ commit }) {
    commit('AUTOUP_CURPORTS', await getPortTable())
  },
  reqPortsOpen({ commit }, open) {
    return new Promise((res, rej) => {
      openPort(open.path, open.cfg, (err) => {
        if (err) {
          if (err != 'Error: Port is opening') {
            console.log(err)
            return rej(err)
          }
        }
        let path = []
        path.push(open.path)
        commit('ADD_OPENPORTOBJ', path)
        return res(open.path)
      })
    })
  },
  reqPortsClose({ commit }, path) {
    return new Promise((res, rej) => {
      closePort(path, (err) => {
        if (err) {
          console.log(err)
          return rej(err)
        }

        commit("DEL_OPENPORTOBJ", path)
        return res(path)
      })
    })
  },
  reqPortReadMessage({ commit,state },port){
    rxPort(port,state.readTimer,(readMessage)=>{
      commit("UPPER_READMESSAGE",{port,readMessage})
    })
  },
  reqPortSendMessage({ commit }, { port, sendMessage, encoding }) {
    return new Promise((res, rej) => {
      console.log('发送数据到达')
      commit("UPPER_SENDMESSAGE", { port, sendMessage })
      txPort(port, sendMessage, encoding, (err, number) => {
        console.log('hahahah')
        if (err) {
          return rej(err)
        }
        commit("UPPER_SENDMESSAGE", { port, sendMessage })
        return res(number)
      })
    })
  },
  upperPortSettings({ commit }, { port, cfg }) {
    return new Promise((res, rej) => {
      upPortSettings(port, cfg, (err) => {
        if (err) {
          return rej(err)
        }
        console.log(getPortSettings)
        return res()
      })
    })
  }

}

export default {
  state,
  getters,
  mutations,
  actions
}
